package com.caocaog.market.toccpt.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.toccpt.mapper.OrderContrastCcptMapper;
import com.caocaog.market.toccpt.marketmodel.OrderBaseInfo;
import com.caocaog.market.toccpt.marketmodel.OrderContrastCcpt;
import com.caocaog.market.toccpt.service.OrderContrastCcptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 曹操来了向曹操跑腿甩单记录
 *
 *  * @author liguang
 *  * @date 2021-12-31
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderContrastCcptServiceImpl extends ServiceImpl<OrderContrastCcptMapper, OrderContrastCcpt> implements OrderContrastCcptService {

    @Override
    public int insert(JSONObject jObj) {
        if(null==jObj){
            return 0;
        }
        //解析字符串
        log.info("向跑腿甩单，返回的内容转换为字符串："+ jObj.toString());
        // 存向跑腿甩单的数据记录（只有甩单成功才会记录）
        OrderContrastCcpt entity = new OrderContrastCcpt();
        if(Integer.parseInt(jObj.get("isSuccess").toString())==1) {
            entity.setCcptOrderNo(String.valueOf(jObj.get("ccptOrderNo")));
            entity.setCcptOrderSid(Integer.parseInt(String.valueOf(jObj.get("ccptOrderSid"))));
            entity.setCcptOrderMemberSid(Integer.parseInt(String.valueOf(jObj.get("ccptOrderMemberSid"))));
            entity.setIsSuccess(1);
        }
        entity.setMarketOrderId(String.valueOf(String.valueOf(jObj.get("marketOrderId"))));
        entity.setMarketOrderNo(String.valueOf(String.valueOf(jObj.get("marketOrderNo"))));
        entity.setMarketOrderPayNo(String.valueOf(String.valueOf(jObj.get("marketPayNo"))));
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        entity.setCreateBy((null==loginUser || StringUtils.isBlank(loginUser.getUsername())) ? "admin": loginUser.getUsername());
        entity.setCreateTime(DateUtils.getDate());
        entity.setId(IdWorker.getIdStr(entity));
        entity.setLockVersion(1);
        entity.setDelFlag(0);
        log.info("插入OrderContrastCcpt 记录  数据");
        return super.getBaseMapper().insert(entity);
    }

    /**
     * 先查询是不是外卖订单，从mk_order_base表中查询type字段；type=1表示外卖订单；
     *      如果不是外卖订单，则不向跑腿进行甩单操作；
     *      如果是外卖订单，则去mk_shop_takeout表中查询oder_model字段，order_model=2自动发单
     *
     *      mk_order_base表中的type=1外卖   且  mk_shop_takeout表中的order_model=2自动发单   才会执行向跑腿甩单
     */
    @Override
    public boolean findOderModel(String payNo) {
        OrderBaseInfo orderBaseInfo = super.getBaseMapper().findOrderModel(payNo);
        if(null==orderBaseInfo){
            return false;
        }
        String orderModel = orderBaseInfo.getOrderModel();
        if(StringUtils.isBlank(orderModel)){
            return false;
        }
        // 发单模式等于2表示自动发单
        if(orderModel.equals("2")){
            return true;
        }
        return false;
    }

    @Override
    public OrderContrastCcpt findRecordByMarketOrderId(String marketOrderId) {
        QueryWrapper<OrderContrastCcpt> queryWrapper = new QueryWrapper();
        // is_success=1代表向曹操跑腿甩单成功，倒序排列取第一条记录
        queryWrapper.eq("market_order_id",marketOrderId).eq("is_success",1).orderByDesc("create_time");
        queryWrapper.last(" limit 1");
        OrderContrastCcpt orderContrastCcpt = super.getBaseMapper().selectOne(queryWrapper);
        return orderContrastCcpt;
    }


    @Override
    public OrderContrastCcpt findByCcptOrderSid(Integer ccptOrderSid) {
        log.info(String.valueOf(ccptOrderSid));
        if (Objects.isNull(ccptOrderSid) || ccptOrderSid == 0) return new OrderContrastCcpt();
        return baseMapper.selectOne(new LambdaQueryWrapper<OrderContrastCcpt>()
                .eq(OrderContrastCcpt::getCcptOrderSid, ccptOrderSid));
    }



}
